package com.poizon.infrastructure.idem.config.change.listener;

import cn.hutool.core.util.StrUtil;
import com.poizon.infrastructure.center.config.core.event.listener.ConfigChangeListenerImpl;
import com.poizon.infrastructure.center.config.core.event.strategy.ConfigChangeEventStrategy;
import com.poizon.infrastructure.idem.core.domain.entity.IdemEntity;
import com.poizon.infrastructure.idem.core.domain.value.config.IdemConstants;
import com.poizon.infrastructure.idem.core.recovery.IdemDbStoreFailover;
import com.poizon.infrastructure.idem.core.repo.IIdemDbStoreRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;

import java.util.Properties;

@Slf4j
@ConditionalOnClass(value = {ConfigChangeEventStrategy.class, ConfigChangeListenerImpl.class})
@ConditionalOnBean(value = ConfigChangeListenerImpl.class)
public class IdemDbStoreConfigChangeStrategy implements ConfigChangeEventStrategy {
    @Override
    public String getChangedProperty(Properties properties) {
        String config = properties.getProperty(IdemConstants.DB_STORE_TYPE_CONFIG);
        return config;
    }

    @Override
    public Boolean support(Properties properties) {
        String config = getChangedProperty(properties);
        return StrUtil.isNotBlank(config);
    }

    @Override
    public void configChange(Properties properties) {
        // todo: 切换的过程中,需要对幂等操作加锁,暂停业务,防止部分业务数据在旧存储中,部分在新存储中
        String newDbType = getChangedProperty(properties);
        IIdemDbStoreRepo oldDbStoreRepo = IdemEntity.iIdemDbStoreRepo;
        String oldDbStoreType = IdemConstants.IDEM_DB_STORE_TYPE;
        if (StrUtil.equals(newDbType, oldDbStoreType)) {
            return;
        }

        Boolean SUCCESS = IdemDbStoreFailover.changeIdemDbStoreInstantly(newDbType);
        if (SUCCESS) {
            log.info(">成功变更幂等底层存储类型 {} -> {}",oldDbStoreType, newDbType);
        } else {
            log.error(">变更幂等底层存储类型 {} -> {} 失败", oldDbStoreType, newDbType);
        }
    }
}
